package com.test.springai.controller;

import java.util.List;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 9/4/25 3:49 PM
 * @modifiedBy:
 * @version: 1.0
 */
@RestController
@RequestMapping("/advisor")
public class MemoryMessageAdvisorController {
  private static final String CONVERSATIONID = "conversationid";
  private final ChatClient chatClient;
  private final InMemoryChatMemoryRepository chatMemoryRepository =
      new InMemoryChatMemoryRepository();
  private final int MAX_MESSAGE = 100;
  private final MessageWindowChatMemory messageWindowChatMemory =
      MessageWindowChatMemory.builder()
          .chatMemoryRepository(chatMemoryRepository)
          .maxMessages(MAX_MESSAGE)
          .build();

  public MemoryMessageAdvisorController(ChatClient.Builder builder) {
    this.chatClient =
        builder
            .defaultAdvisors(MessageChatMemoryAdvisor.builder(messageWindowChatMemory).build())
            .build();
  }

  @GetMapping("/call")
  public String call(
      @RequestParam(value = "query", defaultValue = "你好，我的外号是影子，请记住呀") String query,
      @RequestParam(value = "conversationid", defaultValue = "yingzi") String conversationId) {
    return chatClient
        .prompt(query)
        .advisors(a -> a.param(CONVERSATIONID, conversationId))
        .call()
        .content();
  }

  @GetMapping("/messages")
  public List<Message> messages(
      @RequestParam(value = "conversationid", defaultValue = "yingzi") String conversationId) {
    return messageWindowChatMemory.get(conversationId);
  }
}
